var baseExtend = "../../script/";

layui.define(['zepto'], function (exports) {
  layui.config({
    base: baseExtend
  }).use(['justchatApiMgr'], function () {
    var $ = layui.zepto;
    var justchatApiMgr = layui.justchatApiMgr;
    var $outer = $('#otherPage');
    $outer.on('userpageInit', userpageInit);

    function popConfirm(obj) {
      var content = obj.content;
      var ok = obj.ok;
      var cancel = obj.cancel;

      var $body = $("body")
      $layer = $(`<div id="isClearHistoryLayer" style="position:fixed;left:0;top:0;width:100%;height:100%;z-index:198910140;background:rgba(0,0,0,.5)">
          <div  style="left:calc(50% - 150px);top:calc(50% - 110px);position:absolute;width:300px;min-height:150px;box-sizing:border-box;background:#fff;padding:30px 40px;">
              <p style="text-align:center;font-size:18px;margin-bottom:20px;">拉黑用户</p>
              <div style="margin-bottom:20px;font-size:14px;">${content}</div>
              <div style="text-align:center;">
                  <button  style="margin-left:0px;height:36px;line-height:30px;padding:2px 20px;" class="cancel-btn layui-btn layui-btn-primary">取消</button>
                  <button style="height:36px;line-height:30px;margin-left:20px;padding:2px 20px;" class="confirm-btn layui-btn">确定</button>
              </div>
          </div>
          </div>`);

      $layer.appendTo($body);

      var $cancelBtn = $("#isClearHistoryLayer .cancel-btn");
      var $confimBtn = $("#isClearHistoryLayer .confirm-btn");
      $cancelBtn.on('click', function () {
        $layer.remove();
        cancel && cancel()
      })
      $confimBtn.on('click', function () {
        ok && ok();

        $layer.remove();
      })
    }

    function userpageInit() {
      var targetId = arguments[1];
      var currentRemark = '';
      var nickname = '';
      __pageInit();

      function __pageInit() {
        var state = {};

        isEidtAddWatcher();
        pullBlackPageAddWatcher();

        function isEidtAddWatcher() {
          var isEdit = false;
          Object.defineProperty(state, 'isEdit', {
            get: function () {
              return isEdit;
            },
            set: function (newValue) {
              isEdit = newValue;
              if (isEdit) {
                __initEdit();
              } else {
                __initMain();
              }
            },
            enumerable: true,
            configurable: true
          })
        }

        function pullBlackPageAddWatcher() {
          var pullBlackPage = false;
          Object.defineProperty(state, 'pullBlackPage', {
            get: function () {
              return pullBlackPage;
            },
            set: function (newValue) {
              pullBlackPage = newValue;
              if (pullBlackPage) {
                __initPullBlackPage();
              } else {
                __initMain();
              }
            },
            enumerable: true,
            configurable: true
          })
        }

        __initMain();

        // 初始化编辑备注页面
        function __initEdit() {
          $outer.find('#head p').text('编辑备注');
          $outer.find('#head .goback').off('click').on('click', function () {
            state.isEdit = false;
          })

          var ok = $('<span id="edit-confirm" class="edit-confirm">确定</span>');
          ok.on('click', function () {
            var newRemark = $('.remark-input').val();
            justchatApiMgr.updateRemark({
              target_id: targetId,
              name: newRemark
            }, function () {
              layer.msg('编辑成功');
              state.isEdit = false;
            }, function () {
              layer.msg('编辑失败');
              state.isEdit = false;
            })
          })

          $outer.find('#head').append(ok);

          var tempEdit = `
          <div class="user">
              <div class="user-main" id="remarkEdit">
                <p class="remark-title">备注：</p>
                <textarea type="text"  placeholder="请输入备注" class="remark-input">${currentRemark}</textarea>
            </div>
          </div>
          `

          $outer.find('#content').html(tempEdit);

        }

        // 初始化拉黑页面
        function __initPullBlackPage() {
          $outer.find('#head p').text('拉黑用户');
          $outer.find('#head .goback').off('click').on('click', function () {
            state.pullBlackPage = false;
          })

          var ok = $('<span id="edit-confirm" class="edit-confirm">确定</span>');
          ok.on('click', function () {
            var reson = $('.remark-input').val();
            popConfirm({
              content: '确定要拉黑【' + nickname + '】吗？',
              ok: function () {
                justchatApiMgr.pullBlack({
                  target_id: targetId,
                  remark: reson
                }, function () {
                  layer.msg('拉黑成功');
                  state.pullBlackPage = false;
                })
              }
            })
          })

          $outer.find('#head').append(ok);

          var tempEdit = `
          <div class="user">
              <div class="user-main" id="remarkEdit">
                <p class="remark-title">拉黑原因：</p>
                <textarea type="text" value="" placeholder="请输入拉黑原因" class="remark-input"></textarea>
            </div>
          </div>
          `

          $outer.find('#content').html(tempEdit);

        }


        function __initMain() {
          $outer.find('#head p').text('用户信息');
          $outer.find('#head .goback').on('click', function () {
            $outer.hide();
          })
          $outer.find('#edit-confirm').remove();

          var temp = `
          <div class="user">
              <div class="user-main">
                <div class="info-item">
                    <p class="info-item-title">所属商户：</p>
                    <p class="info-detail" id="platform_name"></p>
                </div>

                <div class="info-item">
                    <p class="info-item-title">用户id：</p>
                    <p class="info-detail mch_user_id" id="userId"></p>
                    <textarea class="info-detail-textarea mch_user_id" id="userIdHide"></textarea>
                    <a id="copy" href="javascript:;" data-clipboard-action="cut" data-clipboard-target="userId"
                        class="info-item-btn">复制</a>
                </div>

                <div class="info-item">
                    <p class="info-item-title">用户昵称：</p>
                    <p class="info-detail" id="nickname"></p>
                </div>

                <!-- <div class="info-item">
                    <p class="info-item-title">操作系统：</p>
                    <p class="info-detail">IOS</p>
                </div> -->

                <div class="info-item">
                    <p class="info-item-title">VIP等级：</p>
                    <p class="info-detail" id="level"></p>
                </div>

                <div class="info-item">
                    <p class="info-item-title">交易次数：</p>
                    <p class="info-detail" id="success_order_count"></p>
                </div>

                <div class="info-item">
                  <p class="info-item-title">备注：</p>
                  <p class="info-detail" id="remark"></p>
                  <a href="javascript:;" class="info-item-btn" id="editBtn">编辑</a>
                </div>

                <a class="close-user layui-hide" id="pullBlack" href="javascript:;">拉黑用户</a>
            </div>
          </div>
          `

          $outer.find('#content').html(temp);

          getUserInfo();

          $('#pullBlack').on('click', function () {
            if ($(this).hasClass('layui-disabled')) return
            state.pullBlackPage = true;
          });

          //监听编辑
          $('#editBtn').on('click', function () {
            state.isEdit = true;
          })


          function getUserInfo() {
            var userId = targetId;
            justchatApiMgr.getUserInfo(userId, function (result) {
              if (result.status == 0) {
                var data = result.data
                $("#platform_name").text(data.platform.name);
                $(".mch_user_id").text(data.mch_user_id);
                $("#nickname").text(data.nickname);
                $("#level").text(__levelToText(data.level));
                $("#success_order_count").text(data.success_order_count);
                $("#remark").text(data.remark);
                currentRemark = data.remark;
                nickname = data.nickname;
                if (data.is_blacklist) {
                  $('#pullBlack').addClass('layui-disabled').text('已拉黑').removeClass('layui-hide');
                } else {
                  $('#pullBlack').removeClass('layui-disabled').text('拉黑用户').removeClass('layui-hide');
                }

                // 更新本地缓存
                var friendsInfo = JSON.parse(localStorage.getItem("friendsInfo")) || {};
                friendsInfo[userId] = data
                localStorage.setItem('friendsInfo', JSON.stringify(friendsInfo))
              }
            }, function () {
              layer.msg('获取用户信息失败')
            }, true);
          }

          $('#copy').on('click', function () {
            $('#userIdHide').get(0).select();
            document.execCommand("Copy");
            layer.msg('复制成功 '+$('#userIdHide').text());
          })
        }

        function __levelToText(level) {
          switch (level) {
            case 0:
              return '免费用户'
            case 1:
              return '普通用户'
            case 2:
              return '中级用户'
            case 3:
              return '高级用户'
            default:
              return ''
          }
        }

        function popConfirm(obj) {
          var content = obj.content;
          var ok = obj.ok;
          var cancel = obj.cancel;

          var $body = $("body")
          $layer = $(`<div id="isClearHistoryLayer" style="position:fixed;left:0;top:0;width:100%;height:100%;z-index:198910140;background:rgba(0,0,0,.5)">
                <div  style="left:calc(50% - 150px);top:calc(50% - 110px);position:absolute;width:300px;min-height:150px;box-sizing:border-box;background:#fff;padding:30px 40px;">
                    <p style="text-align:center;font-size:18px;margin-bottom:20px;">拉黑用户</p>
                    <div style="margin-bottom:20px;font-size:14px;">${content}</div>
                    <div style="text-align:center;">
                        <button  style="margin-left:0px;height:36px;line-height:30px;padding:2px 20px;" class="cancel-btn layui-btn layui-btn-primary">取消</button>
                        <button style="height:36px;line-height:30px;margin-left:20px;padding:2px 20px;" class="confirm-btn layui-btn">确定</button>
                    </div>
                </div>
                </div>`);

          $layer.appendTo($body);

          var $cancelBtn = $("#isClearHistoryLayer .cancel-btn");
          var $confimBtn = $("#isClearHistoryLayer .confirm-btn");
          $cancelBtn.on('click', function () {
            $layer.remove();
            cancel && cancel()
          })
          $confimBtn.on('click', function () {
            ok && ok();

            $layer.remove();
          })
        }
      }
    }

    exports('userpage', userpageInit);
  })
});